import Vue from "vue";
import VueRouter from "vue-router";
import vuex from '../store/index';

Vue.use(VueRouter);

const routes = [{
	path: "/",
	name: "registered",
	component: () => import("../views/registered.vue"),
}, {
	path: "/sign",
	name: "sign",
	component: () => import("../views/sign.vue"),
}, {
	path: "/page",
	name: "page",
	meta: {
		requireAuth: true, // 添加该字段，表示进入这个路由是需要登录的
	},
	redirect: "/odometer",
	component: () => import("../views/backgroundPage.vue"),
	children: [{
		path: '/odometer',
		name: "odometer",
		meta: {
			requireAuth: true, // 添加该字段，表示进入这个路由是需要登录的
		},
		component: () => import("../views/components/odometer.vue"),
	}, {
		path: '/userManage',
		name: "userManage",
		meta: {
			requireAuth: true, // 添加该字段，表示进入这个路由是需要登录的
		},
		component: () => import("../views/components/userManage.vue"),
	}, {
		path: '/articleManage',
		name: "articleManage",
		meta: {
			requireAuth: true, // 添加该字段，表示进入这个路由是需要登录的
		},
		component: () => import("../views/components/articleManage.vue"),
	}, {
		path: '/classifyManage',
		name: "classifyManage",
		meta: {
			requireAuth: true, // 添加该字段，表示进入这个路由是需要登录的
		},
		component: () => import("../views/components/classifyManage.vue"),
	}, {
		path: '/projectManage',
		name: "projectManage",
		meta: {
			requireAuth: true, // 添加该字段，表示进入这个路由是需要登录的
		},
		component: () => import("../views/components/projectManage.vue"),
	}, {
		path: '/discussManage',
		name: "discussManage",
		meta: {
			requireAuth: true, // 添加该字段，表示进入这个路由是需要登录的
		},
		component: () => import("../views/components/discussManage.vue"),
	}]
}];

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
	routes,
});


router.beforeEach((to, from, next) => {
	// console.log(to) // 即将要进入的目标路由对象
	// console.log(from) // 当前导航正要离开的路由
	// next()// 回调函数
	// let userinfo = localStorage.userinfo;
	let userinfo = Storage.prototype.getCanExpireLocal("userinfo");
	// console.log(userinfo);
	if (to.meta.requireAuth) { //进行判断跳到哪个路径的值，如果为false的话不必进行路由守卫/则为true的话进行判断
		if (userinfo == '值已失效' || userinfo == null) {
			next("/sign");
		} else {
			if (to.path == '/odometer' || to.path == '/userManage' || to.path == '/roleManage') {
				if (JSON.parse(userinfo).role == '0') {
					next();
					vuex.commit('changerouteractive', to.path)
					vuex.commit('changeuserinfo', JSON.parse(userinfo))
				} else {
					Vue.prototype.$message({
						type: 'info',
						message: '当前账号没有权限访问该菜单，正在跳往文章管理'
					});
					next("/articleManage");
				}
			} else {
				next();
				vuex.commit('changerouteractive', to.path)
				vuex.commit('changeuserinfo', JSON.parse(userinfo))
			}
		}
	} else {
		next()
	}
})

export default router;
